local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding

function enc(data)
    return ((data:gsub('.', function(x) 
        local r,b='',x:byte()
        for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
        return r;
    end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
        if (#x < 6) then return '' end
        local c=0
        for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
        return b:sub(c+1,c+1)
    end)..({ '', '==', '=' })[#data%3+1])
end

-- decoding
function dec(data)
    data = string.gsub(data, '[^'..b..'=]', '')
    return (data:gsub('.', function(x)
        if (x == '=') then return '' end
        local r,f='',(b:find(x)-1)
        for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
        return r;
    end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
        if (#x ~= 8) then return '' end
        local c=0
        for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
            return string.char(c)
    end))
end

local xx=[[
"{"dtmfflag": "false", "match_nothing": 0, "wav_filename": "xtw_rec/25.wav", "log_file": "/root/log_sellbot/logic/20180105_5000/c27bd7c0-e87b-48a4-a08c-1cf5817ee423_logic.log", "intent": 100, "dtmftimeout": "10", "end": 0, "user_attentions": "[('\u5f00\u573a\u767d', 1), ('\u4ef7\u683c', 1)]", "accurate_intent": "E", "sentence": "\u5229\u606f", "used_time_ms": 5.101999999999999, "answer": "\u662f\u8fd9\u6837\uff0c\u6cf0\u56fd\u7684\u8d37\u6b3e\u5229\u7387\u9ad8\u8fbe6.5%\uff0c\u52a0\u4e0a\u5728\u6cf0\u56fd\u4e00\u822c\u5c01\u9876\u524d\u9700\u8981\u4ea4\u9f5050%\u9996\u4ed8\uff0c\u6240\u4ee5\u6211\u4eec\u8fd9\u4e48\u4f4e\u7684\u4ef7\u683c\u5f88\u5c11\u6709\u4eba\u8981\u6c42\u8d37\u6b3e\u7684\uff0c\u5982\u679c\u60a8\u9700\u8981\u8d37\u6b3e\uff0c\u6211\u4eec\u53ef\u4ee5\u5e2e\u60a8\u529e\u7406\u4fe1\u7528\u8d37\u6b3e\uff0c\u5229\u606f\u6700\u4f4e\u53ef\u4ee55.5%\u6700\u957f\u8d37\u6b3e5\u5e74\uff0c\u6700\u9ad830\u4e07\u3002\u5177\u4f53\u7684\u8fd8\u8bf7\u60a8\u5230\u552e\u697c\u5904\u9762\u8c08\uff0c\u7a0d\u540e\u628a\u5730\u5740\u53d1\u7ed9\u60a8\u3002", "state": "\u4ef7\u683c", "dtmfend": "", "reason": "\u5728\u5fd9\u6b21\u6570:1</br>\u547d\u4e2d\u5173\u952e\u8bcd:\u5f00\u8f66", "dtmflen": "1", "dtmfresult": "-1"}"
]]

x = enc(xx)
print(enc(xx))

y = dec(x)
print(y)
